import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import Small from './small';
import BackRouter from '@/pages/CapacityStudy/KnowledgeSmartMaintenance/backRouter'
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Icon, Tooltip, Form, Button, Input, Spin, Table, message, InputNumber, Drawer, Progress, Modal } from 'antd';
import styles from "./index.less";
import { runInThisContext } from 'vm';


const FormItem = Form.Item;
class CheckList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      login: false,
      totala: 0,
      page: 1,
      pageSize: 10,
      similarList: [],
      query: '', // 搜索的关键词
      minWordCount: '', // 最小字数
      maxWordCount: '', // 最大字数
      minAskCount: '',  // 最小询问次数
      maxAskCount: '',  // 最大询问次数
      order: 'wordCount',   // 排序字段
      sort: 'asc',  //  排序方式，asc：升序，desc：降序,
      dxList: [],
      selectedRowKeys: [],
      Drawera: false,
      DrawerNoLogin: false,
      percent: 0,
      num: 0,
    };
  }

  componentDidMount() {
    this.knowledgeQuestionList()
  }

  knowledgeQuestionList = () => {
    this.setState({ login: true })
    const { dispatch, currentUser } = this.props;
    const { page, pageSize, query, minWordCount, maxWordCount, minAskCount, maxAskCount, order, sort } = this.state
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeQuestionList',
        payload: {
          query,
          minWordCount,
          maxWordCount,
          minAskCount,
          maxAskCount,
          order,
          sort,
          page,
          limit: pageSize,
        },
        callback: res => {
          console.log('问题库列表', res);
          if (res.code === 0) {
            this.setState({
              similarList: res.data.list,
              totala: res.data.total,
              login: false
            })
            // this.drjl('unknown')
          }
        },
      });
    });
  }

  pageWay = (a) => {
    console.log(a)

    this.setState({ page: a, dxList: [], selectedRowKeys: [], }, () => {
      this.knowledgeQuestionList()
    })

  }

  onShowSizepageWay = (a, b) => {
    console.log(a, b)
    this.setState({ page: a, pageSize: b }, () => {
      this.knowledgeQuestionList()
    })

  }

  // 表单数据
  userInfo = () => {
    return this.props.form.getFieldsValue();
    // 使用方法 
    // let user  = this.userInfo()
    // console.log(user)
  }

  // 删除回调
  knowledgeQuestionDelete = (ids, url) => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: url,
        payload: {
          ids,
        },
        callback: res => {
          console.log('删除问题库中的问题', res);
          if (res.code === 0) {
            message.success(`${res.msg}`)
            this.setState({
              login: false,
              selectedRowKeys: [],
              dxList: []
            }, () => {
              this.knowledgeQuestionList()
            })
          }
        },
      });
    });
  }

  // 引导黑名单回调
  knowledgeQuestionDelete = (ids, url) => {
    if (ids.length === 0) {
      message.error('请先选择需要操作内容')
    } else {
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: url,
          payload: {
            ids,
          },
          callback: res => {
            console.log('删除问题库中的问题', res);
            if (res.code === 0) {
              message.success(`${res.msg}`)
              this.setState({
                login: false,
                selectedRowKeys: [],
                dxList: [],
              }, () => {
                this.knowledgeQuestionList()
              })
            }
          },
        });
      });
    }

  }

  deleteTable = (item) => { // knowledgeQuestionDelete
    this.setState({ login: true })
    console.log(item)
    this.knowledgeQuestionDelete(Array(item.id), 'knowledgeSmartMaintenance/knowledgeQuestionDelete')
  }

  deleteTables = (item) => {
    this.setState({ login: true })
    console.log(item)
    this.knowledgeQuestionDelete(Array(item.id), 'knowledgeSmartMaintenance/questionBlacklistMoveIn')
  }

  handleOpen = (item) => {
    console.log(item)

  }

  // 批量删除
  batchDelete = () => {
    const { dxList } = this.state
    console.log(dxList)
    this.knowledgeQuestionDelete(dxList, 'knowledgeSmartMaintenance/knowledgeQuestionDelete')
  }

  // 全部删除
  allBatchDelete = () => {
    Modal['confirm']({
      title: '删除任务',
      content: '确定全部删除吗？',
      okText: "删除",
      cancelText: "取消",
      onOk: () => {
        const { dispatch, currentUser } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'knowledgeSmartMaintenance/knowledgeQuestionClear',
            payload: { isBlacklist: false },
            callback: res => {
              console.log('删除所有内容', res);
              if (res.code === 0) {
                message.success(`${res.msg}`)
                this.knowledgeQuestionList()
              }
            },
          });
        });
      },
      onCancel() {
        console.log('onCancel')
      }
    })
  }

  // 批量移到黑名单
  moveBlacklist = () => { // questionBlacklistMoveIn
    const { dxList } = this.state
    console.log(dxList)
    this.knowledgeQuestionDelete(dxList, 'knowledgeSmartMaintenance/questionBlacklistMoveIn')
  }

  backRouter = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push({
      pathname: '/capacity/knowledgeSmartMaintenance'
    }));
  }



  // 查询
  theQuery = () => {
    let user = this.userInfo()
    console.log(user)
    this.setState({
      query: user.inputA,
      minWordCount: user.InputNumber1,
      maxWordCount: user.InputNumber2,
      minAskCount: user.InputNumber3,
      maxAskCount: user.InputNumber4,
    }, () => {
      this.knowledgeQuestionList()
    })
  }

  // 排序
  pXhandleChange = (pagination, filters, sorter, ) => {
    console.log(sorter) // "ascend" 升序 "descend"降序 参数 order  field->dataIndex
    if (sorter.field === "wordCount") { // 字数排序
      if (sorter.order === 'ascend') { // 升序
        this.setState({
          order: 'wordCount',
          sort: 'asc'
        }, () => {
          this.knowledgeQuestionList()
        })
      }
      if (sorter.order === 'descend') { // 降序
        this.setState({
          order: 'wordCount',
          sort: 'desc'
        }, () => {
          this.knowledgeQuestionList()
        })
      }
    }
    if (sorter.field === "askCount") { // 询问次数排序
      if (sorter.order === 'ascend') { // 升序
        this.setState({
          order: 'askCount',
          sort: 'asc'
        }, () => {
          this.knowledgeQuestionList()
        })
      }
      if (sorter.order === 'descend') { // 降序
        this.setState({
          order: 'askCount',
          sort: 'desc'
        }, () => {
          this.knowledgeQuestionList()
        })
      }
    }

  }

  // ---- 抽屉弹框-----
  showDrawer = () => {
    console.log(this.state.num)
    // knowledgeQuestionChatStatus
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeQuestionChatStatus',
        payload: {},
        callback: res => {
          console.log('清除闲聊问题状态', res);
          if (res.code === 0) {
            if (res.data.status === 'none') {
              const { dispatch, currentUser } = this.props;
              this.reqRef = requestAnimationFrame(() => {
                dispatch({
                  type: 'knowledgeSmartMaintenance/knowledgeQuestionChatSubmit',
                  payload: {},
                  callback: res => {
                    console.log('开始闲聊任务', res);
                    if (res.code === 0) {
                      this.showDrawer()
                    }
                  },
                });
              });
            }
            if (res.data.status === 'wait') {
              this.setState({
                visiblea: true,
                DrawerNoLogin: false
              }, () => {
                this.percent()
              });
            }
            if (res.data.status === 'success' && this.state.num === 0) {
              this.setState({
                visiblea: true,
                DrawerNoLogin: true
              });
            }
            if (res.data.status === 'success' && this.state.num === 1) {
              this.setState({
                DrawerNoLogin: true,
                num: 0,
              });
            }
          }
        },
      });
    });
  };


  // 进度条任务
  percent = () => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgequestionChatProcess',
        payload: {},
        callback: res => {
          console.log('获取任务进度', res);
          if (res.process === 1) {
            this.setState({ num: res.process }, () => {
              this.showDrawer()
            })
          } else if (res.process === 0) {
            this.setState({ percent: res.process }, () => {
              setTimeout(() => {
                this.setState({ num: res.process }, () => {
                  this.percent()
                })
              }, 1000)
            })
          } else {
            const number = res.process
            console.log(Math.floor(Number(number * 100)))
            this.setState({ percent: Math.floor(Number(number * 100)) }, () => {
              setTimeout(() => {
                this.setState({ num: res.process }, () => {
                  this.percent()
                })
              }, 500)
            })
          }

        },
      });
    });
  }

  onClose = () => {
    this.setState({
      visiblea: false,
    });
  };

  // 子组件回调
  gress = (a) => {
    console.log(a)
    if (a === 0) {
      this.showDrawer()
    }
  }


  render() {
    const { getFieldDecorator } = this.props.form;
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        let a = []
        selectedRows.map((item, index) => {
          a.push(item.id)
        })
        this.setState({ dxList: a, selectedRowKeys, })
      },
    };
    const columns = [
      {
        title: '问题',
        width: 'calc(30vw)',
        dataIndex: 'question',
        render(item) {
          return (
            // <div className={styles.wtbj}>{item}</div>
            <div dangerouslySetInnerHTML={{ __html: item }}></div>
          )
        }
      },
      {
        title: '字数',
        width: 'calc(10vw)',
        sorter: (a, b) => { },
        dataIndex: 'wordCount',
      },
      {
        title: '询问次数',
        dataIndex: 'askCount',
        sorter: (a, b) => { },
        width: 'calc(10vw)',
      },
      {
        title: '操作',
        width: 'calc(15vw)',
        render: (text, item) => {
          return <div className={styles.flexBj}>
            <div
              style={{ marginRight: 10, marginBottom: 4 }}
              className={styles.buttongl}
              onClick={() => { this.deleteTable(item) }}>
              <span><Icon size="small" type="delete" style={{ marginRight: 5 }} />
              </span><span>删除</span>
            </div>

            <div
              style={{ marginRight: 10, marginBottom: 4 }}
              className={styles.buttong2}
              onClick={() => { this.deleteTables(item) }}>
              <span style={{ whiteSpace: 'nowrap' }}><Icon size="small" type="user-delete" style={{ marginRight: 5 }} />
              </span><span style={{ whiteSpace: 'nowrap' }}>转移到黑名单</span>
            </div>
          </div>
        }
      },
    ]
    return (
      <Suspense fallback={< PageLoading />} >
        <PageHeaderWrapper>
          <div style={{ minHeight: 'calc(100vh - 150px)', background: '#ffffff' }}>
            <Row className={styles.colorBackground}>
              <Col style={{ padding: 10, }} xs={24}>
                <span className={styles.title}>
                  <span>问题库</span>
                  <BackRouter pathname='/capacity/knowledgeSmartMaintenance'></BackRouter>
                </span>

              </Col>
            </Row>
            <Card
              bordered={false}
            >
              <Row>
                <Form style={{ marginBottom: 20 }} layout="inline">
                  <FormItem className='zdyButtonA'>
                    <Button onClick={this.batchDelete} type='primary'>批量删除</Button>
                  </FormItem>
                  <FormItem className='zdyButtonD'>
                    <Button onClick={this.allBatchDelete} type='primary'>全部删除</Button>
                  </FormItem>
                  <FormItem className='zdyButtonB'>
                    <Button onClick={this.moveBlacklist} type='primary'>移到黑名单</Button>
                  </FormItem>
                  <FormItem className='zdyButtonC'>
                    <Button onClick={this.showDrawer} type='primary'>清除闲聊问题</Button>
                  </FormItem>
                  <span style={{ float: "right" }}>
                    <FormItem>
                      {getFieldDecorator('inputA', {
                        initialValue: '',
                      })(
                        <Input onPressEnter={() => { this.theQuery() }} placeholder="多个关键词空格隔开" style={{ width: 200 }}></Input>
                      )}
                    </FormItem>
                    <FormItem>
                      <div>
                        <span style={{ marginRight: 10 }}>字数</span>
                        {getFieldDecorator('InputNumber1', {
                          initialValue: '',
                        })(
                          <InputNumber min={0} max={100} placeholder="最小值" style={{ width: 90 }} />
                        )}
                        <span style={{ margin: '0px 10px' }}>—</span>
                        {getFieldDecorator('InputNumber2', {
                          initialValue: '',
                        })(
                          <InputNumber min={0} max={100} placeholder="最大值" style={{ width: 90 }} />
                        )}
                      </div>
                    </FormItem>
                    <FormItem>
                      <div>
                        <span style={{ marginRight: 10 }}>询问次数</span>
                        {getFieldDecorator('InputNumber3', {
                          initialValue: '',
                        })(
                          <InputNumber min={0} max={100} placeholder="最小值" style={{ width: 90 }} />
                        )}
                        <span style={{ margin: '0px 10px' }}>—</span>
                        {getFieldDecorator('InputNumber4', {
                          initialValue: '',
                        })(
                          <InputNumber min={0} max={100} placeholder="最大值" style={{ width: 90 }} />
                        )}
                      </div>
                    </FormItem>
                    <FormItem className='zdyButtonZ'>
                      <Button onClick={this.theQuery} type="primary" icon="search">查询</Button>
                    </FormItem>
                  </span>
                </Form>
                <Spin spinning={this.state.login}>
                  <Table
                    // className='zdyTable'
                    rowSelection={rowSelection}
                    onChange={this.pXhandleChange}
                    style={{ padding: '20px 0px 0px 0px' }}
                    columns={columns}
                    dataSource={this.state.similarList}// 数据
                    // onChange={this.handleChange}
                    pagination={{  // 分页
                      total: this.state.totala,
                      pageSize: this.state.pageSize,  // 显示几条一页
                      current: this.state.page, // 当前页
                      showSizeChanger: true,  // 是否显示可以设置几条一页的选项
                      showQuickJumper: true,
                      onChange: this.pageWay,
                      onShowSizeChange: this.onShowSizepageWay
                    }}
                  />
                </Spin>
              </Row>
            </Card>
            <Drawer
              width='900'
              title="清除闲聊问题"
              placement="right"
              onClose={this.onClose}
              visible={this.state.visiblea}
            >
              {this.state.DrawerNoLogin ? <Small ProgressName={this.state.visiblea} gress={this.gress} ></Small> : <div className={styles.progrees} style={{ minHeight: 'calc(100vh - 150px)', background: '#ffffff' }}>
                  <div className={styles.center} style={{ color: '#000',width:169 }}><span>正在智能识别闲聊知识库</span><span className={styles.loading}></span></div>
                <div style={{ height: 30 }}></div>
                <Progress
                  type="circle"
                  percent={this.state.percent}
                  width={90}
                  strokeWidth={8}
                />
                <div style={{ height: 30 }}></div>
                <Button onClick={this.onClose} type='primary'>关闭</Button>
              </div>}
            </Drawer>
          </div>
        </PageHeaderWrapper>
      </Suspense >
    );
  }
}

export default connect(({ user }) => ({ // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(CheckList));